/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */

package controllers

import (
	"encoding/json"
	"prim-server/common"
	"prim-server/errcode"
	"prim-server/logger"
	"prim-server/primservice/validator"
	productionService "prim-server/service/production"
)

// 管理可购买资源列表
const (
	//获取可购买资源列表
	GetProductionListURL = "/v1/production/list"
	//管理员增加可购买资源列表
	AddProductionURL = "/v1/partner/production/add"
	//管理员删除可购买资源列表
	DeleteProductionURL = "/v1/partner/production/delete"
)

type ProductionController struct {
	CommonController
}

// 新增产品
func (pc *ProductionController) AddProduction() {
	req := common.AddProductionRequest{}
	if err := json.Unmarshal(pc.Ctx.Input.RequestBody, &req); err != nil {
		logger.Error("AddProduction Unmarshal error: %v", err)
		pc.HandleErrCode(errcode.E.Base.RequestInvalid.WithErr(err))
		return
	}
	if err := validator.Validate(&req); err != nil {
		pc.HandleErrCode(errcode.E.Base.RequestInvalid.WithErr(err))
		return
	}
	if err := pc.CheckUserIdFromSession(req.UserId); err != nil {
		pc.HandleErrCode(errcode.E.Base.ErrorMessage.WithMessage("用户检验失败"))
		return
	}
	if len(req.AddProducts) == 0 {
		pc.HandleErrCode(errcode.E.Base.ErrorMessage.WithMessage("请求增加的产品为空"))
		return
	}
	//参数校验--TODO
	//iframeURL长度不能超过2048
	if err := productionService.AddProduction(req.AddProducts); err != nil {
		pc.HandleErrCode(errcode.E.Internal.Internal.WithErr(err))
		return
	}
	pc.HandleBusinessSuccess()
}

// 删除产品
func (pc *ProductionController) DeleteProduction() {
	userId := pc.Ctx.Input.Query("userId")
	productionId := pc.Ctx.Input.Query("productionId")
	if len(userId) == 0 || len(productionId) == 0 {
		pc.HandleErrCode(errcode.E.Base.RequestInvalid.WithMessage("参数错误"))
		return
	}
	if err := pc.CheckUserIdFromSession(userId); err != nil {
		pc.HandleErrCode(errcode.E.Base.ErrorMessage.WithMessage("用户检验失败"))
		return
	}
	if _, err := productionService.GetProductionById(productionId); err != nil {
		pc.HandleErrCode(errcode.E.Base.ErrorMessage.WithErr(err))
		return
	}
	if err := productionService.DeleteProduction(productionId); err != nil {
		pc.HandleErrCode(errcode.E.Base.ErrorMessage.WithErr(err))
		return
	}
	pc.HandleBusinessSuccess()
}

// 查询可购买资源列表
func (pc *ProductionController) QueryProductionList() {
	products, err := productionService.GetProductionAll(nil, nil, nil, nil, nil)
	if err != nil {
		pc.HandleErrCode(errcode.E.Base.ErrorMessage.WithErr(err))
		return
	}
	response := productionService.BuildReponseForGetProductionAll(products)
	pc.HandleBusinessObj(response)
}
